package cc.ufinity.networkdiagnose.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.os.Looper;
import android.telephony.TelephonyManager;

/** 
* @author 008 ��Application��ͳһ�����쳣�����浽SD����Ŀ¼��TeamWork_LOG�ļ����£����10����
*/ 
public class CrashHandler implements UncaughtExceptionHandler { 
	/** 
	* �Ƿ�����־���,��Debug״̬�¿���, ��Release״̬�¹ر�����ʾ�������� 
	* */ 
	public static final boolean DEBUG = true; 
	/** ϵͳĬ�ϵ�UncaughtException������ */ 
	private Thread.UncaughtExceptionHandler mDefaultHandler; 
	/** CrashHandlerʵ�� */ 
	private static final CrashHandler INSTANCE = new CrashHandler(); 
	
	/** �����Context���� */ 
	private Context mContext; 
	/** ��ֻ֤��һ��CrashHandlerʵ�� */ 
	private CrashHandler() { 
	} 
	
	/** ��ȡCrashHandlerʵ�� ,����ģʽ */ 
	public static CrashHandler getInstance() { 
		return INSTANCE; 
	} 
	
	/** 
	* ��ʼ��,ע��Context����, ��ȡϵͳĬ�ϵ�UncaughtException������, ���ø�CrashHandlerΪ�����Ĭ�ϴ����� 
	* 
	* @param ctx 
	*/ 
	public void init(Context ctx) { 
		mContext = ctx; 
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); 
		Thread.setDefaultUncaughtExceptionHandler(this); 
	} 
	
	/** 
	* ��UncaughtException����ʱ��ת��ú��������� 
	*/ 
	public void uncaughtException(Thread thread, Throwable ex) { 
		if (!handleException(ex) && mDefaultHandler != null) { 
			// ����û�û�д�������ϵͳĬ�ϵ��쳣������������ 
			mDefaultHandler.uncaughtException(thread, ex); 
		} else { // ����Լ��������쳣���򲻻ᵯ������Ի�������Ҫ�ֶ��˳�app 
			try { 
				Thread.sleep(3000); 
			} catch (InterruptedException e) {} 
			android.os.Process.killProcess(android.os.Process.myPid()); 
			System.exit(10); 
		} 
	} 
	
	/** 
	* �Զ��������,�ռ�������Ϣ ���ʹ��󱨸�Ȳ������ڴ����. �����߿��Ը���Լ���������Զ����쳣�����߼� 
	* 
	* @return true��?����쳣�������������쳣�� 
	*         false��?������쳣(���Խ���log��Ϣ�洢����)Ȼ�󽻸��ϲ�(����͵���ϵͳ���쳣����)ȥ���? 
	*         ����˵����true���ᵯ���Ǹ�������ʾ��false�ͻᵯ�� 
	*/ 
	private boolean handleException(final Throwable ex) { 
		if (ex == null) { 
			return false; 
		} 
		// final String msg = ex.getLocalizedMessage(); 
		final StackTraceElement[] stack = ex.getStackTrace(); 
		final String message = ex.getMessage(); 
		new Thread() { 
			@Override 
			public void run() { 
				Looper.prepare(); 
	            FileOutputStream fos = null;
	            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	            Date curDate = new Date(System.currentTimeMillis());
	    		String fileName = formatter.format(curDate) + ".log";
				File file = null;
				
				try {
					/*File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/NetworkDiagnose_LOG/");
					fileDir.mkdir();
					file = new File(Environment.getExternalStorageDirectory() + "/NetworkDiagnose_LOG/"+ fileName);*/
					
					File fileDir = mContext.getFilesDir();
					String path = fileDir.getParent() + File.separator + "log" + File.separator;
					File fileDir2 = new File(path);
					fileDir2.mkdir();
					file = new File(path + fileName);
					if (!file.exists()) {
		            	file.createNewFile();
		            }
					
					fos = new FileOutputStream(file, true); 
					
					String model = android.os.Build.MODEL;
					String version = android.os.Build.VERSION.RELEASE;
					TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
					String id = tm.getSubscriberId();
					String info = "[机型： " + model + " 系统版本：" + version + " : " + id + " ]\n";
					fos.write(info.getBytes()); 
					try {
						fos.write(message.getBytes()); 
					} catch(Exception e) {
						fos.write("---- 错误信息 --------\n".getBytes()); 
					}
					for (int i = 0; i < stack.length; i++) { 
						fos.write((stack[i].toString()+"\n").getBytes()); 
					} 
					fos.flush(); 
					fos.close(); 
				} catch (Exception e) { 
					e.printStackTrace();
				} finally {
					if(fos != null) {
						try {
							fos.flush(); 
							fos.close();
							fos = null;
						} catch (IOException e) {} 
					}
				}
				Looper.loop(); 
			} 
		
		}.start(); 
		return false; 
	} 

}
